package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.feign.UserFeign;
import com.example.mapper.CodeMapper;
import com.example.pojo.AuthCode;
import com.example.service.CodeService;
import com.example.utils.MailUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.Date;

/**
 * @author lbq
 * @version 1.0
 * @date 2021/3/13 22:50
 */
@Service
@Slf4j
public class CodeServiceImpl extends ServiceImpl<CodeMapper, AuthCode> implements CodeService {

    @Autowired
    private UserFeign userFeign;
    @Autowired
    private CodeMapper codeMapper;

    /**
     * 发送验证码到邮箱
     *
     * @param email 邮箱地址
     * @return
     */
    @Override
    public String create(String email) {
        // 验证邮箱是否已经注册
        String isRegister = userFeign.isRegister(email);
        if (!Boolean.parseBoolean(isRegister)) {
            String code = RandomStringUtils.randomNumeric(6);
            // 新建一个线程发送邮件
            new Thread(() -> {
                try {
                    MailUtil.sendMsg("13580532615@163.com", "注册验证码", code);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
            // 保存验证码
            long now = Instant.now().toEpochMilli();
            AuthCode authCode = new AuthCode()
                    .setCode(code)
                    .setEmail(email)
                    .setCreatetime(new Date(now))
                    .setExpiretime(new Date(now + 600000));
            boolean isOk = save(authCode);
            return Boolean.valueOf(isOk).toString();
        }
        return isRegister;
    }

    /**
     * 校验验证码是否正确
     *
     * @param email 邮箱地址
     * @param code  验证码
     * @return
     */
    @Override
    public String validate(String email, String code) {
        try {
            QueryWrapper<AuthCode> wrapper = new QueryWrapper<>();
            wrapper.eq(AuthCode.EMAIL, email).eq(AuthCode.CODE, code).gt(AuthCode.EXPIRETIME, new Date());
            AuthCode authCode = codeMapper.selectOne(wrapper);
            return authCode != null ? "0" : "1";
        } catch (Exception e) {
            log.error(e.getMessage());
            return "2";
        }
    }
}
